package com.cogu.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by cogu on 2017/12/24.
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * Pointcut注解，可以切向某个具体类的一个或多个方法
     */
    @Pointcut("execution(public * com.cogu.controller.GirlController.*(..))")
    public void log(){
    }

    /**
     * 通过"log()"来隐式加载log函数
     * 这里是对请求的相关信息记录
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        logger.info("url={}",request.getRequestURI());
        //method
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //function
        logger.info("function={}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //param
        logger.info("args={}",joinPoint.getArgs());
    }

    /**
     * 在执行完请求后调用
     */
    @After("log()")
    public void doAfter(){
        logger.info("2222222");
    }

    /**
     * returning里写的是这个方法的入参
     * 这里获取响应的信息，由于不知道获取的是何种类型以及多少，所以使用Object类型
     * @param object
     */
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturning(Object object){
        logger.info("response={}",object.toString());
    }
}
